@{
    ViewData["Title"] = "销售发货订单编辑";
    Layout = null;
}

<link rel="stylesheet" href="~/layui/css/layui.css">
<script src="~/libs/dayjs/dayjs.min.js"></script>

<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-header">
            <h3 id="pageTitle">销售发货订单</h3>
        </div>
        <div class="layui-card-body">
            <form class="layui-form" id="orderForm" lay-filter="orderForm">
                <input type="hidden" name="id" id="orderId">

                <!-- 订单基本信息 -->
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">订单编码</label>
                        <div class="layui-input-inline">
                            <input type="text" name="orderCode" id="orderCode" required lay-verify="required" placeholder="订单编码" autocomplete="off" class="layui-input" readonly>
                        </div>
                        <div class="layui-form-mid">
                            <button type="button" class="layui-btn layui-btn-sm" id="generateCode">生成编码</button>
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">订单日期</label>
                        <div class="layui-input-inline">
                            <input type="text" name="orderDate" id="orderDate" required lay-verify="required" placeholder="订单日期" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                </div>

                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">关联订单</label>
                        <div class="layui-input-inline">
                            <input type="text" name="relatedOrderCode" placeholder="关联订单编码" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">发货类型</label>
                        <div class="layui-input-inline">
                            <input type="text" name="deliveryType" placeholder="发货类型" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                </div>

                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">客户名称</label>
                        <div class="layui-input-inline">
                            <input type="text" name="customerName" id="customerName" required lay-verify="required" placeholder="客户名称" autocomplete="off" class="layui-input" readonly>
                            <input type="hidden" name="customerCode" id="customerCode" value="">
                        </div>
                        <div class="layui-form-mid">
                            <button type="button" class="layui-btn layui-btn-sm" id="selectCustomer">选择客户</button>
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">联系人</label>
                        <div class="layui-input-inline">
                            <input type="text" name="contactPerson" placeholder="联系人" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                </div>

                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">仓库编码</label>
                        <div class="layui-input-inline">
                            <input type="text" name="warehouseCode" id="warehouseCode" placeholder="仓库编码" autocomplete="off" class="layui-input" readonly>
                        </div>
                        <div class="layui-form-mid">
                            <button type="button" class="layui-btn layui-btn-sm" id="selectWarehouse">选择仓库</button>
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">业务员</label>
                        <div class="layui-input-inline">
                            <input type="text" name="salesperson" placeholder="业务员" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                </div>

                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">币别</label>
                        <div class="layui-input-inline">
                            <select name="baseCurrency">
                                <option value="RMB">人民币</option>
                                <option value="USD">美元</option>
                                <option value="EUR">欧元</option>
                                <option value="HKD">港币</option>
                            </select>
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">结算方式</label>
                        <div class="layui-input-inline">
                            <select name="paymentMethod">
                                <option value="月结30天">月结30天</option>
                                <option value="月结45天">月结45天</option>
                                <option value="月结60天">月结60天</option>
                                <option value="现金">现金</option>
                                <option value="预付款">预付款</option>
                            </select>
                        </div>
                    </div>
                </div>

                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">发货地址</label>
                        <div class="layui-input-inline" style="width: 400px;">
                            <input type="text" name="deliveryAddress" placeholder="发货地址" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                </div>

                <div class="layui-form-item layui-form-text">
                    <label class="layui-form-label">备注</label>
                    <div class="layui-input-block">
                        <textarea name="remarks" placeholder="请输入备注" class="layui-textarea"></textarea>
                    </div>
                </div>

                <!-- 订单明细 -->
                <fieldset class="layui-elem-field">
                    <legend>订单明细</legend>
                    <div class="layui-field-box">
                        <!-- 明细工具栏 -->
                        <div class="layui-btn-group" style="margin-bottom: 10px;">
                            <button type="button" class="layui-btn" id="addDetail">添加明细</button>
                            <button type="button" class="layui-btn layui-btn-danger" id="deleteDetail">删除明细</button>
                            <button type="button" class="layui-btn layui-btn-normal" id="importFromSaleOrder">从销售订单导入</button>
                        </div>

                        <!-- 明细表格 -->
                        <table id="detailTable" lay-filter="detailTable"></table>
                    </div>
                </fieldset>

                <!-- 订单汇总信息 -->
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">总数量</label>
                        <div class="layui-input-inline">
                            <input type="text" name="totalQuantity" id="totalQuantity" readonly class="layui-input">
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">总金额</label>
                        <div class="layui-input-inline">
                            <input type="text" name="totalAmount" id="totalAmount" readonly class="layui-input">
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">总包装数</label>
                        <div class="layui-input-inline">
                            <input type="text" name="totalPackages" id="totalPackages" class="layui-input">
                        </div>
                    </div>
                </div>

                <!-- 操作按钮 -->
                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <button type="button" class="layui-btn" id="saveBtn">保存</button>
                        <button type="button" class="layui-btn layui-btn-normal" id="confirmBtn">确认</button>
                        <button type="button" class="layui-btn layui-btn-normal" id="submitBtn">提交审批</button>
                        <button type="button" class="layui-btn layui-btn-normal" id="approveBtn">审批通过</button>
                        <button type="button" class="layui-btn layui-btn-danger" id="rejectBtn">审批拒绝</button>
                        <button type="button" class="layui-btn layui-btn-primary" id="backBtn">返回</button>
                        <button type="button" class="layui-btn layui-btn-primary" id="cancelBtn">取消</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 明细编辑弹窗模板 -->
<script type="text/html" id="detailFormTpl">
    <form class="layui-form" id="detailForm" lay-filter="detailForm" style="margin: 20px;">
        <input type="hidden" name="id">
        <input type="hidden" name="saleOrderId">

        <div class="layui-form-item">
            <label class="layui-form-label">产品编码</label>
            <div class="layui-input-inline">
                <input type="text" name="productCode" id="productCode" required lay-verify="required" placeholder="产品编码" autocomplete="off" class="layui-input" readonly>
            </div>
            <div class="layui-form-mid">
                <button type="button" class="layui-btn layui-btn-sm" id="selectProduct">选择产品</button>
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">产品名称</label>
            <div class="layui-input-block">
                <input type="text" name="productName" required lay-verify="required" placeholder="产品名称" autocomplete="off" class="layui-input" readonly>
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">材质等级</label>
            <div class="layui-input-inline">
                <input type="text" name="materialGrade" placeholder="材质等级" autocomplete="off" class="layui-input">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">颜色</label>
            <div class="layui-input-inline">
                <input type="text" name="color" placeholder="颜色" autocomplete="off" class="layui-input">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">数量</label>
            <div class="layui-input-inline">
                <input type="number" name="deliveryQuantity" required lay-verify="required|number" placeholder="数量" autocomplete="off" class="layui-input">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">单位</label>
            <div class="layui-input-inline">
                <input type="text" name="unit" placeholder="单位" autocomplete="off" class="layui-input">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">金额</label>
            <div class="layui-input-inline">
                <input type="number" name="amountVARCHAR" placeholder="金额" autocomplete="off" class="layui-input">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">仓库编码</label>
            <div class="layui-input-inline">
                <input type="text" name="warehouseCode" placeholder="仓库编码" autocomplete="off" class="layui-input">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">仓库名称</label>
            <div class="layui-input-inline">
                <input type="text" name="warehouseName" placeholder="仓库名称" autocomplete="off" class="layui-input">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">客户PO</label>
            <div class="layui-input-inline">
                <input type="text" name="customerPO" placeholder="客户PO" autocomplete="off" class="layui-input">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">SKU</label>
            <div class="layui-input-inline">
                <input type="text" name="sku" placeholder="SKU" autocomplete="off" class="layui-input">
            </div>
        </div>

        <div class="layui-form-item">
            <div class="layui-input-block">
                <button type="button" class="layui-btn" id="saveDetailBtn">保存</button>
                <button type="button" class="layui-btn layui-btn-primary" id="cancelDetailBtn">取消</button>
            </div>
        </div>
    </form>
</script>

<script src="~/layui/layui.js"></script>
<script>
    layui.use(['form', 'table', 'layer', 'laydate'], function(){
        var form = layui.form;
        var table = layui.table;
        var layer = layui.layer;
        var laydate = layui.laydate;
        var $ = layui.$;

        // 变量初始化
        var orderId = '@ViewBag.Id';
        var isView = (location.href.indexOf('view=1') > -1);
        var orderStatus = 0; // 默认草稿状态

        // 日期控件初始化
        laydate.render({
            elem: '#orderDate',
            type: 'date'
        });

        // 初始化表格
        var detailTable = table.render({
            elem: '#detailTable',
            cols: [[
                {type: 'checkbox', width: 50},
                {field: 'productCode', title: '产品编码', width: 120},
                {field: 'productName', title: '产品名称', width: 150},
                {field: 'materialGrade', title: '材质等级', width: 100},
                {field: 'color', title: '颜色', width: 80},
                {field: 'deliveryQuantity', title: '数量', width: 80},
                {field: 'unit', title: '单位', width: 60},
                {field: 'amountVARCHAR', title: '金额', width: 100},
                {field: 'warehouseCode', title: '仓库编码', width: 100},
                {field: 'warehouseName', title: '仓库名称', width: 120},
                {field: 'customerPO', title: '客户PO', width: 120},
                {field: 'sku', title: 'SKU', width: 120}
            ]],
            data: [],
            limit: 1000
        });

        // 表格双击编辑事件
        table.on('rowDouble(detailTable)', function(obj){
            var data = obj.data;
            if(orderStatus !== 0 && orderStatus !== 4) {
                return; // 只有草稿或拒绝状态可以编辑
            }

            layer.open({
                type: 1,
                title: '编辑明细',
                area: ['600px', '500px'],
                content: $('#detailFormTpl').html(),
                success: function(){
                    // 填充表单
                    form.val('detailForm', {
                        id: data.id,
                        saleOrderId: data.saleOrderId,
                        productCode: data.productCode,
                        productName: data.productName,
                        materialGrade: data.materialGrade,
                        color: data.color,
                        deliveryQuantity: data.deliveryQuantity,
                        unit: data.unit,
                        amountVARCHAR: data.amountVARCHAR,
                        warehouseCode: data.warehouseCode,
                        warehouseName: data.warehouseName,
                        customerPO: data.customerPO,
                        sku: data.sku
                    });

                    // 保存明细
                    $('#saveDetailBtn').on('click', function(){
                        var detailData = form.val('detailForm');
                        var detailId = detailData.id;

                        // 表单验证
                        if(!detailData.productCode){
                            layer.msg('请选择产品');
                            return;
                        }

                        if(!detailData.deliveryQuantity){
                            layer.msg('请输入数量');
                            return;
                        }

                        // 设置amountDECIMAL字段与amountVARCHAR字段值一致
                        detailData.amountDECIMAL = detailData.amountVARCHAR;

                        $.ajax({
                            url: '/SaleSendOrder/UpdateOrderDetail?detailId=' + detailId,
                            type: 'POST',
                            contentType: 'application/json',
                            data: JSON.stringify(detailData),
                            success: function(res){
                                if(res.code === 0){
                                    layer.msg('更新成功');
                                    layer.closeAll('page');

                                    // 刷新明细表格
                                    loadOrderDetails();
                                } else {
                                    layer.msg(res.msg || '更新失败');
                                }
                            }
                        });
                    });

                    // 选择产品
                    $('#selectProduct').on('click', function(){
                        layer.open({
                            type: 2,
                            title: '选择产品',
                            area: ['900px', '600px'],
                            content: '/SaleSendOrder/ProductSelect',
                            btn: ['确定', '取消'],
                            yes: function(index, layero){
                                var iframeWindow = window['layui-layer-iframe' + index];
                                var checkStatus = iframeWindow.layui.table.checkStatus('productTable');
                                var data = checkStatus.data;

                                if(data.length === 0){
                                    layer.msg('请选择产品');
                                    return;
                                }

                                var product = data[0];
                                var detailForm = $('#detailForm');
                                detailForm.find('[name=productCode]').val(product.productCode);
                                detailForm.find('[name=productName]').val(product.productName);
                                detailForm.find('[name=materialGrade]').val(product.material || '');
                                detailForm.find('[name=color]').val(product.color || '');
                                detailForm.find('[name=unit]').val(product.unit || '');
                                // 设置仓库信息
                                detailForm.find('[name=warehouseCode]').val($('#warehouseCode').val());
                                detailForm.find('[name=warehouseName]').val($('#warehouseName').val() || ''); // 从隐藏字段获取仓库名称

                                layer.close(index);
                            }
                        });
                    });
                }
            });
        });

        // 加载订单数据
        function loadOrderData(){
            if(!orderId){
                // 新增订单，设置默认值
                $('#pageTitle').text('新增销售发货订单');
                $('#orderDate').val(dayjs().format('YYYY-MM-DD'));
                generateOrderCode();
                showButtons();
                return;
            }

            // 编辑订单，加载数据
            $('#pageTitle').text(isView ? '查看销售发货订单' : '编辑销售发货订单');

            $.ajax({
                url: '/SaleSendOrder/GetSaleSendOrder?id=' + orderId,
                type: 'GET',
                success: function(res){
                    if(res.code === 0){
                        var data = res.data;
                        orderStatus = data.state;

                        // 填充表单
                        form.val('orderForm', {
                            id: data.id,
                            orderCode: data.orderCode,
                            relatedOrderCode: data.relatedOrderCode,
                            orderDate: dayjs(data.orderDate).format('YYYY-MM-DD'),
                            deliveryType: data.deliveryType,
                            warehouseCode: data.warehouseCode,
                            customerName: data.customerName,
                            contactPerson: data.contactPerson,
                            salesperson: data.salesperson,
                            paymentMethod: data.paymentMethod,
                            baseCurrency: data.baseCurrency,
                            totalAmount: data.totalAmount,
                            totalQuantity: data.totalQuantity,
                            totalPackages: data.totalPackages,
                            deliveryAddress: data.deliveryAddress,
                            remarks: data.remarks
                        });

                        // 加载明细
                        if(data.details && data.details.length > 0){
                            detailTable.reload({
                                data: data.details
                            });
                        }

                        // 设置按钮显示状态
                        showButtons();
                    } else {
                        layer.msg(res.msg || '加载数据失败');
                    }
                }
            });
        }

        // 根据订单状态显示对应的按钮
        function showButtons(){
            // 默认隐藏所有按钮
            $('#saveBtn, #confirmBtn, #submitBtn, #approveBtn, #rejectBtn').hide();

            if(isView){
                // 查看模式，禁用所有输入框
                $('#orderForm input, #orderForm textarea, #orderForm select').prop('disabled', true);
                $('#generateCode, #selectCustomer, #selectWarehouse, #addDetail, #deleteDetail, #importFromSaleOrder').hide();
                return;
            }

            if(!orderId){
                // 新增模式
                $('#saveBtn').show();
                return;
            }

            // 根据订单状态显示按钮
            switch(orderStatus){
                case 0: // 草稿
                    $('#saveBtn, #confirmBtn').show();
                    break;
                case 1: // 已确认
                    $('#submitBtn').show();
                    $('#orderForm input, #orderForm textarea, #orderForm select').prop('disabled', true);
                    $('#generateCode, #selectCustomer, #selectWarehouse, #addDetail, #deleteDetail, #importFromSaleOrder').hide();
                    break;
                case 2: // 审批中
                    $('#approveBtn, #rejectBtn').show();
                    $('#orderForm input, #orderForm textarea, #orderForm select').prop('disabled', true);
                    $('#generateCode, #selectCustomer, #selectWarehouse, #addDetail, #deleteDetail, #importFromSaleOrder').hide();
                    break;
                case 3: // 已审批
                case 4: // 已拒绝
                    $('#orderForm input, #orderForm textarea, #orderForm select').prop('disabled', true);
                    $('#generateCode, #selectCustomer, #selectWarehouse, #addDetail, #deleteDetail, #importFromSaleOrder').hide();
                    if(orderStatus === 4) {
                        $('#saveBtn').show();
                        $('#orderForm input, #orderForm textarea, #orderForm select').prop('disabled', false);
                        $('#generateCode, #selectCustomer, #selectWarehouse, #addDetail, #deleteDetail, #importFromSaleOrder').show();
                    }
                    break;
            }
        }

        // 生成订单编码
        function generateOrderCode(){
            $.ajax({
                url: '/SaleSendOrder/GenerateOrderCode',
                type: 'GET',
                success: function(res){
                    if(res.success){
                        $('#orderCode').val(res.code);
                    } else {
                        layer.msg(res.message || '生成订单编码失败');
                    }
                }
            });
        }

        // 保存订单
        function saveOrder(){
            // 获取表单数据 - 修复这里的form引用
            var layuiForm = layui.form;
            var formData = layuiForm.val('orderForm');

            if (!formData) {
                console.error("无法获取表单数据，表单可能不存在或未正确初始化");
                layer.msg('表单数据获取失败', {icon: 2});
                return;
            }

            console.log("获取到表单数据:", formData);

            // 转换字段名为首字母大写，与DTO属性匹配
            var submitData = {
                OrderCode: formData.orderCode || '',
                RelatedOrderCode: formData.relatedOrderCode || '',
                OrderDate: formData.orderDate || dayjs().format('YYYY-MM-DD'),
                DeliveryType: formData.deliveryType || '标准发货',
                WarehouseCode: formData.warehouseCode || '',
                CustomerCode: $('#customerCode').val() || '',
                CustomerName: formData.customerName || '',
                ContactPerson: formData.contactPerson || '无',
                Salesperson: formData.salesperson || '未分配',
                PaymentMethod: formData.paymentMethod || '月结30天',
                BaseCurrency: formData.baseCurrency || 'RMB',
                TotalAmount: parseFloat(formData.totalAmount || 0),
                TotalQuantity: parseFloat(formData.totalQuantity || 0),
                TotalPackages: parseInt(formData.totalPackages || 0, 10),
                DeliveryAddress: formData.deliveryAddress || '公司地址',
                Remarks: formData.remarks || ''
            };

            // 如果是编辑，添加ID字段
            if(formData.id) {
                submitData.Id = parseInt(formData.id, 10);
            }

            // 表单验证
            if(!submitData.OrderCode){
                layer.msg('请输入订单编码');
                return;
            }

            if(!submitData.OrderDate){
                layer.msg('请选择订单日期');
                return;
            }

            if(!submitData.CustomerName){
                layer.msg('请选择客户');
                return;
            }

            // 处理日期格式
            if (submitData.OrderDate) {
                submitData.OrderDate = dayjs(submitData.OrderDate).format('YYYY-MM-DD');
            }

            // 输出完整的提交数据到控制台以便调试
            console.log("完整的提交数据:", submitData);

            // 提交表单
            var url = submitData.Id ? '/SaleSendOrder/UpdateSaleSendOrder?id=' + submitData.Id : '/SaleSendOrder/CreateSaleSendOrder';


            // 显示加载
            var loadIndex = layer.load(1, {
                shade: [0.3, '#333']
            });

            // 使用AJAX提交表单，以便获取返回结果
            $.ajax({
                url: url,
                type: 'POST',
                data: submitData,
                success: function(res) {
                    console.log(res);
                    layer.msg('保存成功', {icon: 1, time: 1000}, function() {
                        // 跳转到列表页
                        location.href = '/SaleSendOrder/Index';
                    });
                }
            });
        }

        // 计算订单总金额和总数量
        function calculateTotal(){
            var data = table.cache.detailTable || [];
            var totalAmount = 0;
            var totalQuantity = 0;

            $.each(data, function(index, item){
                if(item.amountVARCHAR) totalAmount += parseFloat(item.amountVARCHAR);
                if(item.deliveryQuantity) totalQuantity += parseFloat(item.deliveryQuantity);
            });

            $('#totalAmount').val(totalAmount.toFixed(2));
            $('#totalQuantity').val(totalQuantity);
        }

        // 事件绑定
        $('#generateCode').on('click', generateOrderCode);

        // 选择客户
        $('#selectCustomer').on('click', function(){
            layer.open({
                type: 2,
                title: '选择客户',
                area: ['900px', '600px'],
                content: '/SaleSendOrder/CustomerSelect',
                btn: ['确定', '取消'],
                yes: function(index, layero){
                    var iframeWindow = window['layui-layer-iframe' + index];
                    var checkStatus = iframeWindow.layui.table.checkStatus('customerTable');
                    var data = checkStatus.data;

                    if(data.length === 0){
                        layer.msg('请选择客户');
                        return;
                    }

                    var customer = data[0];
                    $('#customerName').val(customer.customerName);
                    $('#customerCode').val(customer.customerCode || customer.id);

                    layer.close(index);
                }
            });
        });

        // 选择仓库
        $('#selectWarehouse').on('click', function(){
            layer.open({
                type: 2,
                title: '选择仓库',
                area: ['900px', '600px'],
                content: '/SaleSendOrder/WarehouseSelect',
                btn: ['确定', '取消'],
                yes: function(index, layero){
                    var iframeWindow = window['layui-layer-iframe' + index];
                    var checkStatus = iframeWindow.layui.table.checkStatus('warehouseTable');
                    var data = checkStatus.data;

                    if(data.length === 0){
                        layer.msg('请选择仓库');
                        return;
                    }

                    var warehouse = data[0];
                    $('#warehouseCode').val(warehouse.id);
                    // 保存仓库名称
                    $('<input>').attr({
                        type: 'hidden',
                        id: 'warehouseName',
                        name: 'warehouseName',
                        value: warehouse.warehouseName
                    }).appendTo('#orderForm');

                    layer.close(index);
                }
            });
        });

        // 添加明细
        $('#addDetail').on('click', function(){
            // 判断是否选择了客户
            if(!$('#customerName').val()){
                layer.msg('请先选择客户');
                return;
            }

            var formId = orderId || '';
            if(!formId){
                layer.msg('请先保存订单');
                return;
            }

            layer.open({
                type: 1,
                title: '添加明细',
                area: ['600px', '500px'],
                content: $('#detailFormTpl').html(),
                success: function(){
                    form.val('detailForm', {
                        saleOrderId: formId
                    });

                    // 选择产品
                    $('#selectProduct').on('click', function(){
                        layer.open({
                            type: 2,
                            title: '选择产品',
                            area: ['900px', '600px'],
                            content: '/SaleSendOrder/ProductSelect',
                            btn: ['确定', '取消'],
                            yes: function(index, layero){
                                var iframeWindow = window['layui-layer-iframe' + index];
                                var checkStatus = iframeWindow.layui.table.checkStatus('productTable');
                                var data = checkStatus.data;

                                if(data.length === 0){
                                    layer.msg('请选择产品');
                                    return;
                                }

                                var product = data[0];
                                var detailForm = $('#detailForm');
                                detailForm.find('[name=productCode]').val(product.productCode);
                                detailForm.find('[name=productName]').val(product.productName);
                                detailForm.find('[name=materialGrade]').val(product.material || '');
                                detailForm.find('[name=color]').val(product.color || '');
                                detailForm.find('[name=unit]').val(product.unit || '');
                                // 设置仓库信息
                                detailForm.find('[name=warehouseCode]').val($('#warehouseCode').val());
                                detailForm.find('[name=warehouseName]').val($('#warehouseName').val() || ''); // 从隐藏字段获取仓库名称

                                layer.close(index);
                            }
                        });
                    });

                    // 保存明细
                    $('#saveDetailBtn').on('click', function(){
                        var detailData = form.val('detailForm');

                        // 表单验证
                        if(!detailData.productCode){
                            layer.msg('请选择产品');
                            return;
                        }

                        if(!detailData.deliveryQuantity){
                            layer.msg('请输入数量');
                            return;
                        }

                        // 设置amountDECIMAL字段与amountVARCHAR字段值一致
                        detailData.amountDECIMAL = detailData.amountVARCHAR;

                        // 提交明细
                        $.ajax({
                            url: '/SaleSendOrder/AddOrderDetail',
                            type: 'POST',
                            contentType: 'application/json',
                            data: JSON.stringify({
                                saleOrderId: orderId,
                                saleOrderProductId1: Number(detailData.saleOrderProductId1) || null,
                                saleOrderProductId2: Number(detailData.saleOrderProductId2) || null,
                                productCode: detailData.productCode,
                                productName: detailData.productName,
                                materialGrade: detailData.materialGrade || '',
                                color: detailData.color || '',
                                deliveryQuantity: detailData.deliveryQuantity,
                                unit: detailData.unit || '',
                                amountVARCHAR: detailData.amountVARCHAR,
                                amountDECIMAL: detailData.amountVARCHAR, // 使用相同值
                                warehouseCode: detailData.warehouseCode,
                                warehouseName: detailData.warehouseName || '',
                                customerPO: detailData.customerPO || '',
                                sku: detailData.sku || ''
                            }),
                            success: function(res){
                                if(res.code === 0){
                                    layer.msg('添加成功');
                                    layer.closeAll('page');

                                    // 刷新明细表格
                                    loadOrderDetails();
                                } else {
                                    layer.msg(res.msg || '添加失败');
                                }
                            }
                        });
                    });

                    $('#cancelDetailBtn').on('click', function(){
                        layer.closeAll('page');
                    });
                }
            });
        });

        // 删除明细
        $('#deleteDetail').on('click', function(){
            var checkStatus = table.checkStatus('detailTable');
            var data = checkStatus.data;

            if(data.length === 0){
                layer.msg('请选择要删除的明细');
                return;
            }

            layer.confirm('确定要删除选中的明细吗？', function(index){
                var id = data[0].id;

                $.ajax({
                    url: '/SaleSendOrder/DeleteOrderDetail?detailId=' + id,
                    type: 'POST',
                    success: function(res){
                        if(res.code === 0){
                            layer.msg('删除成功');
                            loadOrderDetails();
                        } else {
                            layer.msg(res.msg || '删除失败');
                        }
                    }
                });

                layer.close(index);
            });
        });

        // 从销售订单导入
        $('#importFromSaleOrder').on('click', function(){
            // 判断是否选择了客户和仓库
            if(!$('#customerName').val()){
                layer.msg('请先选择客户');
                return;
            }

            if(!$('#warehouseCode').val()){
                layer.msg('请先选择仓库');
                return;
            }

            var formId = orderId || '';
            if(!formId){
                layer.msg('请先保存订单');
                return;
            }

            layer.open({
                type: 2,
                title: '选择销售订单',
                area: ['900px', '600px'],
                content: '/SaleSendOrder/SaleOrderSelect',
                btn: ['确定', '取消'],
                yes: function(index, layero){
                    var iframeWindow = window['layui-layer-iframe' + index];
                    var checkStatus = iframeWindow.layui.table.checkStatus('saleOrderTable');
                    var data = checkStatus.data;

                    if(data.length === 0){
                        layer.msg('请选择销售订单');
                        return;
                    }

                    var saleOrderId = data[0].id;

                    $.ajax({
                        url: '/SaleSendOrder/ImportFromSaleOrder',
                        type: 'POST',
                        data: {
                            saleOrderId: saleOrderId,
                            saleSendOrderId: formId
                        },
                        success: function(res){
                            if(res.code === 0){
                                layer.msg('导入成功');
                                layer.close(index);
                                loadOrderDetails();
                            } else {
                                layer.msg(res.msg || '导入失败');
                            }
                        }
                    });
                }
            });
        });

        // 加载订单明细
        function loadOrderDetails(){
            if(!orderId) return;

            $.ajax({
                url: '/SaleSendOrder/GetOrderDetails?orderId=' + orderId,
                type: 'GET',
                success: function(res){
                    if(res.code === 0){
                        detailTable.reload({
                            data: res.data
                        });
                        calculateTotal();
                    } else {
                        layer.msg(res.msg || '加载明细失败');
                    }
                }
            });
        }

        // 保存按钮
        $('#saveBtn').on('click', function(){
            // 增加调试信息
            console.log("保存按钮被点击");

            // 表单验证
            if(!$('#orderCode').val()){
                layer.msg('请生成订单编码');
                return;
            }

            if(!$('#orderDate').val()){
                layer.msg('请选择订单日期');
                return;
            }

            if(!$('#customerName').val()){
                layer.msg('请选择客户');
                return;
            }

            // 尝试保存订单
            try {
                saveOrder();
            } catch (error) {
                console.error("保存过程中发生异常:", error);
                layer.msg('保存过程中发生错误: ' + error.message, {icon: 2});
            }
        });

        // 确认按钮
        $('#confirmBtn').on('click', function(){
            if(!orderId){
                layer.msg('请先保存订单');
                return;
            }

            layer.confirm('确定确认该订单吗？确认后将无法修改！', function(index){
                $.ajax({
                    url: '/SaleSendOrder/ConfirmOrder',
                    type: 'POST',
                    data: {id: orderId},
                    success: function(res){
                        if(res.code === 0){
                            layer.msg('确认成功');
                            loadOrderData();
                        } else {
                            layer.msg(res.msg || '确认失败');
                        }
                    }
                });
                layer.close(index);
            });
        });

        // 提交审批按钮
        $('#submitBtn').on('click', function(){
            layer.confirm('确定提交审批吗？', function(index){
                $.ajax({
                    url: '/SaleSendOrder/SubmitForApproval',
                    type: 'POST',
                    data: {id: orderId},
                    success: function(res){
                        if(res.code === 0){
                            layer.msg('提交审批成功');
                            loadOrderData();
                        } else {
                            layer.msg(res.msg || '提交审批失败');
                        }
                    }
                });
                layer.close(index);
            });
        });

        // 审批通过按钮
        $('#approveBtn').on('click', function(){
            layer.confirm('确定审批通过吗？', function(index){
                $.ajax({
                    url: '/SaleSendOrder/ApproveOrder',
                    type: 'POST',
                    data: {id: orderId},
                    success: function(res){
                        if(res.code === 0){
                            layer.msg('审批通过成功');
                            loadOrderData();
                        } else {
                            layer.msg(res.msg || '审批通过失败');
                        }
                    }
                });
                layer.close(index);
            });
        });

        // 审批拒绝按钮
        $('#rejectBtn').on('click', function(){
            layer.confirm('确定拒绝审批吗？', function(index){
                $.ajax({
                    url: '/SaleSendOrder/RejectOrder',
                    type: 'POST',
                    data: {id: orderId},
                    success: function(res){
                        if(res.code === 0){
                            layer.msg('拒绝审批成功');
                            loadOrderData();
                        } else {
                            layer.msg(res.msg || '拒绝审批失败');
                        }
                    }
                });
                layer.close(index);
            });
        });

        // 返回按钮
        $('#backBtn').on('click', function(){
            location.href = '/SaleSendOrder/Index';
        });

        // 取消按钮
        $('#cancelBtn').on('click', function(){
            layer.confirm('确定要取消编辑吗？未保存的内容将会丢失', {
                btn: ['确定','取消']
            }, function(){
                // 确定取消，返回列表页
                location.href = '/SaleSendOrder/Index';
            });
        });

        // 初始化页面
        loadOrderData();
    });
</script> 